package cfca.paperless.client.servlet.customer;

import java.io.File;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.SealLogBean;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.servlet.PaperlessManagerClient;
import cfca.paperless.client.util.Base64;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.PdfSealUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.sadk.DonePdfSeal;
import cfca.seal.sadk.PrePdfReader;
import cfca.seal.sadk.PrePdfSeal;
import cfca.seal.sadk.PrePdfSealExtra;
import cfca.seal.sadk.PrePdfSealExtra.SignatureOpacity;

public class testSealDownAndLogUpload_YiFangDa {

    /**
     * 易方达签章下载、签名、签名日志上传等功能测试
     * 
     * @param args
     * @throws IOException
     * @throws
     */
    public static void main(String[] args) throws Exception {
        try {
            //************************************************* 证书下载*******************************************
            PaperlessManagerClient clientBeanOfDownload = new PaperlessManagerClient(PaperlessConfig.managerUrl, 10000, 60000);// 无纸化管理接口的访问URL

            String sealCode = "seal001";
            String sealPassword = "11111111";

            StringBuffer requestXml = new StringBuffer("<Request>");
            requestXml.append("<SealCode>").append(sealCode).append("</SealCode>");
            requestXml.append("<SealPassword>").append(sealPassword).append("</SealPassword>");
            requestXml.append("</Request>");

            // 操作员编码或者机构号
            String operatorCode = PaperlessConfig.operatorCode;
            // 机构编码
            String channelCode = PaperlessConfig.channelCode;

            // 获取签章信息
            String result = clientBeanOfDownload.downloadSeal(requestXml.toString(), operatorCode, channelCode);
            
            // 结果
            String downLoadResult = result;
            String code = StringUtil.getNodeText(result, "Code");
            if ("200".equals(code)) {
                System.out.println(result);
                System.out.println("OK:downloadSeal");
            } else {
                System.out.println("NG:downloadSeal");
                // 处理结果为异常，打印出错误码和错误信息
                System.out.println(result);
            }

            // *******************************************************遍历pdf文件进行签章************************************
            // 日志列表
            List<SealLogBean> sealLogBeans = new ArrayList<SealLogBean>();
            String sealType = "1";// 1：普通签章；2：场景签章，默认1
            String functionType = "sealAutoPdf";// 默认sealAutoPdf
            String bizTypeCode = "B001";// 业务类型，比如：开户、开通网银
            String timestampUsed = "0";// 是否使用时间戳，0：未使用；1：使用
            // 读取pdf文件夹
            String filePath = "./TestData/input/";
            File file = new File(filePath);
            File[] files = file.listFiles();
            // 遍历pdf进行签章
            for (File pdfFile : files) {
                String fileName = pdfFile.getName();
                if (fileName.endsWith(".pdf")) {
                    String pdfFilePath = filePath + fileName;
                    // 计算Hash
                    byte[] pdfFileData = FileUtils.readFileToByteArray(new File(pdfFilePath));
                    String fileHash = PaperlessUtil.bytes2hex(PaperlessUtil.digest(pdfFileData));
                    // 生成prePdfSeal
                    PrePdfSeal prePdfSeal = null;
                    X509Cert x509Cert = null;
                    PrivateKey privateKey = null;
                    // 添加证书信息
                    byte[] imageBytes = Base64.decode(StringUtil.getXmlField(downLoadResult, "SealImage"));
                    String location = "代理人签名";
                    String reason =  "易方达测试";
                    SignLocation signLocation = new SignLocation(location, "R", 0, 0);
                    // 时间戳
                    String timeStampServer[] = new String[] { "", "", "" };
                    byte[] sealedPdf = null;
                    if (downLoadResult.contains("PublicCert")) {//印章含有证书
                        byte[] certData = Base64.decode(StringUtil.getXmlField(downLoadResult, "PublicCert"));
                        x509Cert = new X509Cert(certData);
                        byte[] privateKeyData = Base64.decode(StringUtil.getXmlField(downLoadResult, "PrivateKey").getBytes());
                        privateKey = PdfSealUtil.getRSAPrivateKey(privateKeyData);
                        //生产prePdfSeal
                        prePdfSeal = PdfSealUtil.generatePrePdfSeal(x509Cert, privateKey, imageBytes, 0.87f);
                        // 生成donePdfSeal
                        DonePdfSeal donePdfSeal = new DonePdfSeal();
                        donePdfSeal.initPdfReader(new PrePdfReader(pdfFilePath));
                        donePdfSeal.initPdfSeal(prePdfSeal);
                        PrePdfSealExtra prePdfSealExtra = new PrePdfSealExtra(reason, location);
                        //设置透明度---start 
                        SignatureOpacity signatureOpacity = new SignatureOpacity();
                        signatureOpacity.setFillOpacity(1f);
                        signatureOpacity.setGSBlendMode(1);
                        signatureOpacity.setVisible(true);
                        prePdfSealExtra.setSignatureOpacity(signatureOpacity);
                        //设置透明度---end 
                        //donePdfSeal.initPdfSealExtra(prePdfSealExtra);
                        PdfSealUtil.setSignLocation(donePdfSeal, prePdfSealExtra, signLocation);
                        //进行签章
                        sealedPdf = PdfSealUtil.signPdfSealSingle(pdfFileData, donePdfSeal, signLocation, timeStampServer);
                    }else{//印证没有证书，通过合成图片进行签章
                        sealedPdf = PdfSealUtil.doSealAutoPdfWithoutCert(pdfFileData, imageBytes, signLocation, 0.87f);
                    }
                    
                    // 签名
                    String savedPdfId = GUID.generateId();
                    IoUtil.write("./TestData/output/" + savedPdfId + ".pdf", sealedPdf);
                    // 添加签章日志
                    if (StringUtil.isNotEmpty(timeStampServer[0])) {
                        timestampUsed = "1";
                    }
                    SealLogBean sealLogBean = new SealLogBean(sealCode, sealType, functionType, bizTypeCode, timestampUsed);
                    sealLogBean.setSealLocation(location);
                    sealLogBean.setSealReason(reason);
                    sealLogBean.setFileHash(fileHash);
                    sealLogBeans.add(sealLogBean);
                }
            }

            // ******************************************************* 上传签章日志  *******************************************
            PaperlessManagerClient clientBeanOfUpload = new PaperlessManagerClient(PaperlessConfig.managerUrl, 10000, 60000);// 无纸化管理接口的访问URL
            // 获取上传结果
            String upLoadResult = clientBeanOfUpload.uploadSealLog(PaperlessUtil.buildSealLogsXml(sealLogBeans), operatorCode, channelCode);
            
            String resultCode = StringUtil.getNodeText(upLoadResult, "Code");
            if ("200".equals(resultCode)) {
                System.out.println(upLoadResult);
                System.out.println("OK:uploadSealLog");
            } else {
                System.out.println("NG:uploadSealLog");
                // 处理结果为异常，打印出错误码和错误信息
                System.out.println(upLoadResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
